package com.sean.community.service;

import com.sean.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("all")
public class LikeService {
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 点赞的同时需要维护用户的赞数量，所以需要使用事务
    public void like(int userId, int entityType, int entityId, int entityAuthorId){
        redisTemplate.execute(new SessionCallback<Object>() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                String userLikeKey = RedisKeyUtil.getUserLikeKey(entityAuthorId);
                boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
                operations.multi(); // 开启 Redis 事务
                if(isMember){
                    redisTemplate.opsForSet().remove(entityLikeKey, userId);    // 取消赞
                    redisTemplate.opsForValue().decrement(userLikeKey);         // 减少作者获得的赞
                }else{
                    redisTemplate.opsForSet().add(entityLikeKey, userId);   // 添加赞
                    redisTemplate.opsForValue().increment(userLikeKey);     // 增加作者获得的赞
                }
                return operations.exec(); // 提交事务
            }
        });
    }

    // 查询某实体点赞数量
    public long findEntityLikeCount(int entityType, int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    // 查询某人对某实体的点赞状态
    public int findEntityLikeStatus(int userId, int entityType, int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

    // 查询某个用户获得的赞
    public int findUserLikeCount(int entityAuthorId){
        String userLikeKey = RedisKeyUtil.getUserLikeKey(entityAuthorId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
        return count == null ? 0 : count;
    }
}
